package middlewares

import (
	"gitee.com/jjawesomejj/awesomehttp/system/helper"
	"gitee.com/jjawesomejj/awesomehttp/system/httpContext"
	"gitee.com/jjawesomejj/awesomehttp/system/middlewares"
)

type JsonMiddleware struct {
	middlewares.BaseMiddleware
}

func (baseMiddleware *JsonMiddleware) Handle(ctx *httpContext.HttpContext, next func(ctx2 *httpContext.HttpContext) interface{}) (res interface{}) {
	nectd := next(ctx)
	switch ctx.ResponseContent.(type) {
	case map[string]interface{}:
		response := ctx.ResponseContent.(map[string]interface{})
		if _, ok := response["code"]; !ok {
			response["code"] = 200
		}
		if _, ok := response["pTime"]; !ok {
			response["pTime"] = helper.NowFloat() - ctx.StartAt
		}
		if _, ok := response["remoteAddr"]; !ok {
			response["remoteAddr"] = ctx.Request.RemoteAddr
		}
		ctx.ResponseContent = response
	}
	return nectd
}
